/**
 * 自媒体账号管理页面
 *
 * 提供完整的自媒体账号管理功能，包括：
 * - 账号列表和切换
 * - 账号创建和编辑
 * - 账号记忆设置
 * - 账号偏好配置
 */

import React, { useState, useEffect } from 'react';
import { Plus, Trash2, Star, Users, MessageSquare, BarChart3 } from 'lucide-react';
import { useSocialAccountStore } from '../stores/socialAccountStore';
import { useApiError } from '../hooks/useApiError';
import type { SocialPlatform, CreateSocialAccountRequest } from '../types/socialAccount';

const SocialAccounts: React.FC = () => {
  const {
    accounts,
    activeAccount,
    loading,
    loadAccounts,
    createAccount,
    deleteAccount,
    activateAccount,
  } = useSocialAccountStore();

  const { handleError } = useApiError();

  // const [activeTab, setActiveTab] = useState<'list' | 'create' | 'edit' | 'memory' | 'preferences'>('list');
  // const [selectedAccount, setSelectedAccount] = useState<SocialAccount | null>(null);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState<string | null>(null);

  // Form states
  const [createForm, setCreateForm] = useState<CreateSocialAccountRequest>({
    name: '',
    platform: 'weibo',
    description: '',
    avatar_url: '',
  });

  // const [editForm, setEditForm] = useState<UpdateSocialAccountRequest>({});
  // const [memoryForm, setMemoryForm] = useState<UpdateAccountMemoryRequest>({});
  // const [preferencesForm, setPreferencesForm] = useState<UpdateAccountPreferencesRequest>({});

  useEffect(() => {
    loadAccounts();
  }, [loadAccounts]);

  // Platform options
  const platformOptions: Array<{ value: SocialPlatform; label: string; color: string }> = [
    { value: 'weibo', label: '微博', color: 'bg-red-500' },
    { value: 'wechat', label: '微信公众号', color: 'bg-green-500' },
    { value: 'douyin', label: '抖音', color: 'bg-black' },
    { value: 'xiaohongshu', label: '小红书', color: 'bg-pink-500' },
    { value: 'zhihu', label: '知乎', color: 'bg-blue-600' },
    { value: 'bilibili', label: 'B站', color: 'bg-cyan-500' },
    { value: 'toutiao', label: '今日头条', color: 'bg-red-600' },
    { value: 'baidu', label: '百家号', color: 'bg-blue-700' },
    { value: 'other', label: '其他', color: 'bg-gray-500' },
  ];

  const getPlatformInfo = (platform: SocialPlatform) => {
    return (
      platformOptions.find(p => p.value === platform) || platformOptions[platformOptions.length - 1]
    );
  };

  const handleCreateAccount = async () => {
    try {
      await createAccount(createForm);
      setShowCreateModal(false);
      setCreateForm({ name: '', platform: 'weibo', description: '', avatar_url: '' });
    } catch (error) {
      handleError(error, '创建账号失败');
    }
  };

  const handleDeleteAccount = async (accountId: string) => {
    try {
      await deleteAccount(accountId);
      setShowDeleteConfirm(null);
    } catch (error) {
      handleError(error, '删除账号失败');
    }
  };

  // const handleEditAccount = async () => {
  //   if (!selectedAccount) return;
  //   try {
  //     await updateAccount(selectedAccount.id, editForm);
  //     setActiveTab('list');
  //     setSelectedAccount(null);
  //     setEditForm({});
  //   } catch (error) {
  //     handleError(error, '更新账号失败');
  //   }
  // };

  // const handleUpdateMemory = async () => {
  //   if (!selectedAccount) return;
  //   try {
  //     await updateAccountMemory(selectedAccount.id, memoryForm);
  //   } catch (error) {
  //     handleError(error, '更新账号记忆失败');
  //   }
  // };

  // const handleUpdatePreferences = async () => {
  //   if (!selectedAccount) return;
  //   try {
  //     await updateAccountPreferences(selectedAccount.id, preferencesForm);
  //   } catch (error) {
  //     handleError(error, '更新账号偏好失败');
  //   }
  // };

  // const openEditAccount = (account: SocialAccount) => {
  //   setSelectedAccount(account);
  //   setEditForm({
  //     name: account.name,
  //     description: account.description,
  //     avatar_url: account.avatar_url,
  //   });
  //   setActiveTab('edit');
  // };

  // const openMemorySettings = (account: SocialAccount) => {
  //   setSelectedAccount(account);
  //   const memory = getAccountMemory(account.id);
  //   setMemoryForm({
  //     brand_info: memory?.brand_info,
  //     writing_style: memory?.writing_style,
  //     content_strategy: memory?.content_strategy,
  //     guidelines: memory?.guidelines,
  //   });
  //   setActiveTab('memory');
  // };

  // const openPreferencesSettings = (account: SocialAccount) => {
  //   setSelectedAccount(account);
  //   const preferences = getAccountPreferences(account.id);
  //   setPreferencesForm({
  //     default_settings: preferences?.default_settings,
  //     platform_settings: preferences?.platform_settings,
  //     optimization_preferences: preferences?.optimization_preferences,
  //   });
  //   setActiveTab('preferences');
  // };

  // Render account list
  const renderAccountList = () => (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-bold text-gray-100">自媒体账号管理</h2>
          <p className="text-gray-400 mt-1">管理不同平台的自媒体账号及其个性化设置</p>
        </div>
        <button
          onClick={() => setShowCreateModal(true)}
          className="cursor-pointer flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
        >
          <Plus className="w-4 h-4 mr-2" />
          添加账号
        </button>
      </div>

      {/* Statistics */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-gray-900 border border-gray-800 rounded-xl p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-gray-400">总账号数</p>
              <p className="text-xl font-semibold text-gray-100">{accounts.length}</p>
            </div>
            <Users className="w-6 h-6 text-blue-500" />
          </div>
        </div>
        <div className="bg-gray-900 border border-gray-800 rounded-xl p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-gray-400">激活账号</p>
              <p className="text-xl font-semibold text-gray-100">
                {accounts.filter(a => a.is_active).length}
              </p>
            </div>
            <Star className="w-6 h-6 text-yellow-500" />
          </div>
        </div>
        <div className="bg-gray-900 border border-gray-800 rounded-xl p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-gray-400">平台数</p>
              <p className="text-xl font-semibold text-gray-100">
                {new Set(accounts.map(a => a.platform)).size}
              </p>
            </div>
            <MessageSquare className="w-6 h-6 text-green-500" />
          </div>
        </div>
        <div className="bg-gray-900 border border-gray-800 rounded-xl p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-gray-400">当前激活</p>
              <p className="text-sm font-semibold text-gray-100 truncate">
                {activeAccount?.name || '无'}
              </p>
            </div>
            <BarChart3 className="w-6 h-6 text-purple-500" />
          </div>
        </div>
      </div>

      {/* Account List */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {accounts.map(account => {
          const platformInfo = getPlatformInfo(account.platform);
          return (
            <div
              key={account.id}
              className={`bg-gray-900 border rounded-xl p-6 transition-all ${
                activeAccount?.id === account.id
                  ? 'border-blue-500 ring-2 ring-blue-500/20'
                  : 'border-gray-800 hover:border-gray-700'
              }`}
            >
              <div className="flex items-start justify-between mb-4">
                <div className="flex items-center space-x-3">
                  <div className={`w-3 h-3 rounded-full ${platformInfo.color}`}></div>
                  <div>
                    <h3 className="font-semibold text-gray-100">{account.name}</h3>
                    <p className="text-xs text-gray-400">{platformInfo.label}</p>
                  </div>
                </div>
                <div className="flex items-center space-x-1">
                  {activeAccount?.id === account.id && (
                    <div className="w-2 h-2 rounded-full bg-green-400 animate-pulse"></div>
                  )}
                  <div
                    className={`w-2 h-2 rounded-full ${
                      account.is_active ? 'bg-green-400' : 'bg-gray-500'
                    }`}
                  ></div>
                </div>
              </div>

              {account.description && (
                <p className="text-sm text-gray-300 mb-4 line-clamp-2">{account.description}</p>
              )}

              <div className="flex items-center justify-between">
                <div className="flex space-x-2">
                  {/* Temporarily disabled - to be implemented */}
                  {/* <button
                    onClick={() => openEditAccount(account)}
                    className="cursor-pointer p-1.5 text-gray-400 hover:text-blue-400 hover:bg-gray-800 rounded transition-colors"
                    title="编辑账号"
                  >
                    <Edit className="w-4 h-4" />
                  </button>
                  <button
                    onClick={() => openMemorySettings(account)}
                    className="cursor-pointer p-1.5 text-gray-400 hover:text-purple-400 hover:bg-gray-800 rounded transition-colors"
                    title="记忆设置"
                  >
                    <Brain className="w-4 h-4" />
                  </button>
                  <button
                    onClick={() => openPreferencesSettings(account)}
                    className="cursor-pointer p-1.5 text-gray-400 hover:text-green-400 hover:bg-gray-800 rounded transition-colors"
                    title="偏好设置"
                  >
                    <Settings className="w-4 h-4" />
                  </button> */}
                  <button
                    onClick={() => setShowDeleteConfirm(account.id)}
                    className="cursor-pointer p-1.5 text-gray-400 hover:text-red-400 hover:bg-gray-800 rounded transition-colors"
                    title="删除账号"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>

                {activeAccount?.id !== account.id && (
                  <button
                    onClick={() => activateAccount(account.id)}
                    className="cursor-pointer text-xs px-2 py-1 bg-blue-600 hover:bg-blue-700 text-white rounded transition-colors"
                  >
                    激活
                  </button>
                )}
              </div>
            </div>
          );
        })}

        {accounts.length === 0 && (
          <div className="col-span-full text-center py-12">
            <Users className="w-16 h-16 text-gray-600 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-300 mb-2">暂无账号</h3>
            <p className="text-gray-500 mb-4">创建您的第一个自媒体账号开始使用</p>
            <button
              onClick={() => setShowCreateModal(true)}
              className="cursor-pointer px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
            >
              <Plus className="w-4 h-4 mr-2 inline" />
              添加账号
            </button>
          </div>
        )}
      </div>
    </div>
  );

  // Render create modal
  const renderCreateModal = () => {
    if (!showCreateModal) return null;

    return (
      <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
        <div className="bg-gray-900 border border-gray-800 rounded-xl p-6 w-full max-w-md mx-4">
          <h3 className="text-lg font-semibold text-gray-100 mb-4">创建自媒体账号</h3>

          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">账号名称</label>
              <input
                type="text"
                value={createForm.name}
                onChange={e => setCreateForm({ ...createForm, name: e.target.value })}
                placeholder="输入账号名称"
                className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">平台类型</label>
              <select
                value={createForm.platform}
                onChange={e =>
                  setCreateForm({ ...createForm, platform: e.target.value as SocialPlatform })
                }
                className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                {platformOptions.map(option => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">描述 (可选)</label>
              <textarea
                value={createForm.description}
                onChange={e => setCreateForm({ ...createForm, description: e.target.value })}
                placeholder="简要描述这个账号..."
                rows={3}
                className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
              />
            </div>
          </div>

          <div className="flex justify-end space-x-3 mt-6">
            <button
              onClick={() => setShowCreateModal(false)}
              className="cursor-pointer px-4 py-2 text-gray-400 hover:text-gray-300 transition-colors"
            >
              取消
            </button>
            <button
              onClick={handleCreateAccount}
              disabled={!createForm.name.trim()}
              className="cursor-pointer px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white rounded-lg transition-colors"
            >
              创建
            </button>
          </div>
        </div>
      </div>
    );
  };

  // Render delete confirmation
  const renderDeleteConfirm = () => {
    if (!showDeleteConfirm) return null;

    const account = accounts.find(a => a.id === showDeleteConfirm);
    if (!account) return null;

    return (
      <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
        <div className="bg-gray-900 border border-gray-800 rounded-xl p-6 w-full max-w-sm mx-4">
          <h3 className="text-lg font-semibold text-gray-100 mb-2">确认删除</h3>
          <p className="text-gray-300 mb-4">
            确定要删除账号 <strong>"{account.name}"</strong> 吗？
          </p>
          <p className="text-sm text-gray-400 mb-6">
            此操作将同时删除该账号的记忆数据和偏好设置，且无法恢复。
          </p>

          <div className="flex justify-end space-x-3">
            <button
              onClick={() => setShowDeleteConfirm(null)}
              className="cursor-pointer px-4 py-2 text-gray-400 hover:text-gray-300 transition-colors"
            >
              取消
            </button>
            <button
              onClick={() => handleDeleteAccount(showDeleteConfirm)}
              className="cursor-pointer px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors"
            >
              删除
            </button>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="min-h-screen bg-black text-white p-6">
      <div className="max-w-7xl mx-auto">
        {loading && (
          <div className="flex items-center justify-center py-12">
            <div className="text-center">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mx-auto mb-4"></div>
              <p className="text-gray-400">加载中...</p>
            </div>
          </div>
        )}

        {!loading && renderAccountList()}
        {renderCreateModal()}
        {renderDeleteConfirm()}
      </div>
    </div>
  );
};

export default SocialAccounts;
